﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using Kinect.Toolbox.Collectors;

namespace Kinect.Toolbox.Recording
{
    public class FrameRecorder : IStartableStoppable
    {
        private const int _bufferSize = 20;
        private int _framesCounter;
        private FramesCollector _frameCollector;

        public event EventHandler Stopped;
        public event EventHandler Started;

        public void Start()
        {
            _framesCounter = 0;
            _frameCollector = new FramesCollector(_bufferSize);
            _frameCollector.FrameReady += FrameCollectorOnFrameReady;

            if (Started != null)
            {
                Started(this, EventArgs.Empty);
            }
        }

        public void Stop()
        {
            _frameCollector.FrameReady -= FrameCollectorOnFrameReady;
            _frameCollector = null;

            if (Stopped != null)
            {
                Stopped(this, EventArgs.Empty);
            }
        }

        private void FrameCollectorOnFrameReady(object sender, FrameReadyEventArgs args)
        {
            _framesCounter++;
            if (_framesCounter != _bufferSize)
            {
                return;
            }

            Task.Run(() =>
            {
                var frames = _frameCollector.GetFrames().ToList();
                string recordingPath = ConfigurationManager.AppSettings["RecordFramesPath"] ?? Path.GetTempPath();
                var path = Path.Combine(recordingPath, DateTime.Now.Ticks.ToString());
                using (Stream stream = File.Open(path, FileMode.Create))
                {
                    var bin = new BinaryFormatter();
                    bin.Serialize(stream, frames);
                }
            });
            _framesCounter = 0;
        }
    }
}
